package cn.sinonet.mb.processhandler;

import java.util.HashMap;
import java.util.Map;

import jt.classic.system.ISystemException;

/**
 * MessageProcessHandler Registration Center
 * 
 * @author mido
 * 
 */
public final class MPHCenter {
	private static MPHCenter center;

	private Map centerMap;

	public static MPHCenter getInstance() {
		if (center == null) {
			center = new MPHCenter();
		}
		return center;
	}

	private MPHCenter() {
		this.centerMap = new HashMap();
	}

	public MessageProcessHandler getHandler(String id) throws ISystemException {
		MessageProcessHandler mph = null;

		if (this.centerMap.containsKey(id)) {
			Map handlerInfo = (Map) this.centerMap.get(id);
			String className = (String) handlerInfo.get("PHCLASS");
			try {
				mph = (MessageProcessHandler) Class.forName(className)
						.newInstance();
				mph.reload(new HashMap(handlerInfo));
			} catch (Exception ex) {
				throw new ISystemException("get process handler[" + className
						+ "] instance error.", ex);
			}

		} else {
			throw new ISystemException("can't find process handler[" + id
					+ "] error.");
		}

		return mph;
	}

	public boolean containsHandler(String id) {
		return this.centerMap.containsKey(id);
	}

	public boolean validHandler(String id) {
		boolean rnt = false;

		if (this.centerMap.containsKey(id)) {
			Map handlerInfo = (Map) this.centerMap.get(id);
			String className = (String) handlerInfo.get("PHCLASS");
			try {
				Class.forName(className);
				rnt = true;
			} catch (ClassNotFoundException ex) {
				// do nothing
			}
		}

		return rnt;
	}

	/**
	 * 有效的过程管理器实现类定义
	 * @param className 类名称
	 * @return boolean
	 */
	public static boolean validHandlerClass(String className) {
		boolean rnt = false;

		try {
			Class.forName(className);
			rnt = true;
		} catch (ClassNotFoundException ex) {
			//do nothing
		}

		return rnt;
	}

	public void setHandler(Object id, Map handlerInfo) {
		this.centerMap.put(id, handlerInfo);
	}

}
